<?php
/**
 * Simple PHP Contact Form
 *
 * This file is part of the Simple PHP Contact Form which is subject to the New
 * BSD License {@see LICENSE} which you would be advised to read before using,
 * modifying or redistributing this software.
 *
 * PHP version 5.2
 *
 * @category  Simple-PHP-Contact-Form
 * @package   Application_Controllers_Helpers
 * @author    jah <jah@jahboite.co.uk>
 * @copyright 2010 jah <jah@jahboite.co.uk>
 * @license   New BSD License {@see LICENSE}
 * @version   SVN: $Id$
 * @link      http://code.google.com/p/simple-php-contact-form/
 */


/**
 * Action Helper for loading forms.
 *
 * @category  Simple-PHP-Contact-Form
 * @package   Application_Controllers_Helpers
 * @author    jah <jah@jahboite.co.uk>
 * @copyright 2010 jah <jah@jahboite.co.uk>
 * @license   New BSD License {@see LICENSE}
 * @version   Release: @package_version@
 * @link      http://code.google.com/p/simple-php-contact-form/
 */
class App_Helper_FormLoader extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;

    /**
     * Constructor: initialize plugin loader
     *
     * @return null
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }

    /**
     * Load a form with the provided options.
     *
     * @param string            $name    The name of the form to be loaded
     * @param array|Zend_Config $options Options to be passed to the form
     *                                   constructor.
     *
     * @return Zend_Form
     */
    public function loadForm($name, $options = null)
    {
        $module  = $this->getRequest()->getModuleName();
        $front   = $this->getFrontController();
        $default = $front->getDispatcher()
            ->getDefaultModule();
        if (empty($module)) {
            $module = $default;
        }
        $moduleDirectory = $front->getControllerDirectory($module);
        $formsDirectory  = dirname($moduleDirectory) . '/forms';

        $prefix
            = (('default' == $module) ? '' : ucfirst($module) . '_') . 'Form_';
        $this->pluginLoader->addPrefixPath($prefix, $formsDirectory);

        $name      = ucfirst((string) $name);
        $formClass = $this->pluginLoader->load($name);
        return new $formClass($options);
    }

    /**
     * Strategy pattern: call helper as broker method.
     *
     * @param string            $name    The name of the form to be loaded
     * @param array|Zend_Config $options Options to be passed to the form
     *                                   constructor.
     *
     * @return Zend_Form
     */
    public function direct($name, $options = null)
    {
        return $this->loadForm($name, $options);
    }
}
